package com.fitbet.api.service.impl;

import java.util.Date;
import java.util.HashMap;
import java.util.Map;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.demo2do.core.entity.exception.BusinessException;
import com.demo2do.core.persistence.GenericDaoSupport;
import com.demo2do.core.persistence.annotation.Dao;
import com.demo2do.core.utils.DateFormatUtils;
import com.fitbet.api.Constant;
import com.fitbet.api.dao.UserDao;
import com.fitbet.api.handler.SmsSender;
import com.fitbet.api.service.PaymentCallbackService;
import com.fitbet.api.web.controller.trading.PaymentCallbackController;
import com.fitbet.entity.bet.Bet;
import com.fitbet.entity.bet.UserBet;
import com.fitbet.entity.bet.UserBetStatus;
import com.fitbet.entity.bet.UserBetSupport;
import com.fitbet.entity.trading.OrderType;
import com.fitbet.entity.trading.PaymentRequest;
import com.fitbet.entity.trading.SalesOrder;
import com.fitbet.entity.user.UserTransaction;

/**
 * 
 * @author mohanlan
 *
 */
@Service("paymentCallbackService")
public class PaymentCallbackServiceImpl implements PaymentCallbackService {
    
    private static final Logger logger = LoggerFactory.getLogger(PaymentCallbackController.class);
    
    @Autowired
    private GenericDaoSupport genericDaoSupport;
    
    @Autowired
    private SmsSender smsSender;
    
    @Dao
    private UserDao userDao;

    /*
     * (non-Javadoc)
     * @see com.edoomath.appserver.servcice.PaymentCallbackService#pay(com.edoomath.entity.trade.PaymentRequest, java.lang.String, java.lang.String, java.lang.String, int)
     */
    public SalesOrder pay(PaymentRequest paymentRequest, String orderCode, String payCode, String payTime, int amount) {
        
        SalesOrder salesOrder = this.loadOrder(orderCode);
        
        if(salesOrder == null) {
            throw new BusinessException("支付回调订单数据有误");
        }
        
        // 1. update payment request
        genericDaoSupport.update(paymentRequest.paid(payCode));
        
        // 2. update recharge order
        genericDaoSupport.update(salesOrder.paid());
        
        // 3. update userWallet
        if(salesOrder.getType().equals(OrderType.BET_SUPPORT)) {
            
            UserBet userBet = salesOrder.getUserBet();
            UserBetSupport userBetSupport = salesOrder.getUserBetSupport();
            if(userBet == null || userBetSupport == null) {
                throw new BusinessException("支付回调订单关联数据有误");
            }
            
            genericDaoSupport.update(userBetSupport.paid());
            genericDaoSupport.update(userBet.support(userBetSupport.isSupport(), userBetSupport.getPrice()));
            
            UserTransaction userTransaction = new UserTransaction(userBetSupport.getUser(), 10000, "竞猜", salesOrder.getContent(), false);
            genericDaoSupport.save(userTransaction.init());
            
            Date endDate = userBet.getBet().getEndDate();
            try {
                String content ="【" + Constant.SMS_COMPANY_NAME + "】" + "感谢您关注" + userBet.getBet().getName()+"挑战活动并下注成功，挑战结果将于"+ DateFormatUtils.format(endDate, "MM") +"月"+ DateFormatUtils.format(endDate, "dd") +"日公布，敬请期待。";
                smsSender.sendMessage(userBet.getUser().getMobile(), content);
            } catch (Exception e) {
                logger.error("sms send error", e);
            }
            
        } else if (salesOrder.getType().equals(OrderType.BET)) {
            
            UserBet userBet = salesOrder.getUserBet();
            Bet bet = userBet.getBet();
            
            if(userBet == null || bet == null) {
                throw new BusinessException("支付回调订单关联数据有误");
            }
            
            userBet.setStatus(UserBetStatus.PAID);
            genericDaoSupport.update(userBet);
            genericDaoSupport.update(bet.addThumb(10000));
            
            UserTransaction userTransaction = new UserTransaction(userBet.getUser(), 10000, "契约金", salesOrder.getContent(), false);
            genericDaoSupport.save(userTransaction.init());
            
            Map<String, Object> params = new HashMap<String, Object>();
            params.put("userBet", userBet);
            params.put("user", salesOrder.getUser());
            
            UserBetSupport userBetSupport = genericDaoSupport.searchForObject("FROM UserBetSupport WHERE disabled = false AND userBet = :userBet AND user = :user", params, UserBetSupport.class);
            if(userBetSupport != null) {
                genericDaoSupport.update(userBetSupport.paid());
                genericDaoSupport.update(userBet.support(userBetSupport.isSupport(), userBetSupport.getPrice()));
            }
            
            UserTransaction userTransaction2 = new UserTransaction(userBet.getUser(), 10000, "赌注", salesOrder.getContent(), false);
            genericDaoSupport.save(userTransaction2.init());
        }
        
        return salesOrder;
    }
    
    /**
     * 
     * @param code
     * @return
     */
    private SalesOrder loadOrder(String code) {
        return genericDaoSupport.searchForObject("FROM SalesOrder WHERE disabled = false AND paymentStatus = 'PENDING' AND code = :code", "code", code, SalesOrder.class);
    }

}
